#include "Poco/SharedMemory.h"
#include "Poco/Exception.h"
#include "ShareMem.h"

using namespace SystemTool;

// Construct the obj
ShareMem::ShareMem()
{
}

// Destruct the obj
ShareMem::~ShareMem()
{
    Destroy();
}

// Create a share memory
void ShareMem::Create(std::string strShareMemName,
                      int iMemSize,
                      int iAccessMode,
                      const void *pStartAddr,
                      bool bIsServer)
{
    if (strShareMemName.empty())
    {
        return;
    }
    m_pShareMem = new Poco::SharedMemory(strShareMemName, iMemSize, (Poco::SharedMemory::AccessMode)iAccessMode, pStartAddr, bIsServer);
}

// Read from the share memory
bool ShareMem::Read(char *pData, int iReadSize)
{
    if (pData == nullptr || iReadSize <= 0)
    {
        return false;
    }

    Poco::SharedMemory *pShareMem = (Poco::SharedMemory *)m_pShareMem;
    if (pShareMem == nullptr)
    {
        return false;
    }

    std::copy(pShareMem->begin(), pShareMem->begin() + iReadSize, pData);
    return true;
}

// Write to the share memory
bool ShareMem::Write(const char *pData, int iWriteSize)
{
    if (pData == nullptr || iWriteSize <= 0)
    {
        return false;
    }

    Poco::SharedMemory *pShareMem = (Poco::SharedMemory *)m_pShareMem;
    if (pShareMem == nullptr)
    {
        return false;
    }
    std::copy(pData, pData + iWriteSize, pShareMem->begin());
    return true;
}

// Destroy the share memory
void ShareMem::Destroy()
{
    Poco::SharedMemory *pShareMem = (Poco::SharedMemory *)m_pShareMem;
    if (pShareMem)
    {
        delete pShareMem;
        m_pShareMem = nullptr;
    }
}
